package com.xiaok.netty.server.hander;

import com.xiaok.common.protobuf.Command;
import com.xiaok.common.protobuf.Message;
import com.xiaok.netty.server.components.ChannelRepository;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * 其他业务处理器
 * @author xiaok
 * @create 2020--09-30 10:35
 */
@Component("otherServerHandler")
@ChannelHandler.Sharable
public class OtherServerHandler extends ChannelInboundHandlerAdapter{


    private  Logger log = LoggerFactory.getLogger(this.getClass());
    private final AttributeKey<String> clientInfo = AttributeKey.valueOf("clientInfo");

    @Autowired
    @Qualifier("channelRepository")
    private ChannelRepository channelRepository;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message.MessageBase message= (Message.MessageBase) msg;
        Command.CommandType cmd = message.getCmd();
        if(cmd.equals(Command.CommandType.PUSH_DATA)){
            log.info("业务消息: "+message.getData());
            String data = "this is server bussniss data";
            ChannelFuture channelFuture = ctx.writeAndFlush(createData(message.getClientId(), Command.CommandType.PUSH_DATA_BACK, data).build());
            /* 上一条消息 发送成功后 立马发送业务数据*/
            channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    if(future.isSuccess()){ //发送成功
                        ctx.writeAndFlush(createData(message.getClientId(), Command.CommandType.PUSH_DATA,"start bussniss data。").build());
                    }
                }
            });
        }

        // 释放资源, 保存ByteBuf的消息
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }


    /**
     * 创建 protobuf 的不同类型的数据
     * @param clientId
     * @param cmd
     * @param data
     * @return
     */
    private Message.MessageBase.Builder createData(String clientId, Command.CommandType cmd, String data){
        Message.MessageBase.Builder msg = Message.MessageBase.newBuilder();
        //封装数据
        msg.setClientId(clientId);
        msg.setCmd(cmd);
        msg.setData(data);
        return msg;

    }

}
